<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Affiche;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class AfficheController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        Admin::style(
            <<<CSS
        table {
            text-align: center;
        }
CSS
        );
        $user = Admin::user();
        if ($user->is_admin == -1) {
            $class = $user->affiche()->getQuery();
            $two = new Affiche($class);
        } else {
            $two = new Affiche();
        }
        return Grid::make($two, function (Grid $grid) use ($user) {
            if ($user->is_admin == 1) {
                $grid->model()->with('mechanism');
            }
            $grid->column('id')->sortable();
            if ($user->is_admin == 1) {
                $grid->column('mechanism.name', '所属机构');
            }
            $grid->column('title');
            $grid->column('content');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
        
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
        
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Affiche(), function (Show $show) {
            $show->field('id');
            $show->field('mechanism_id');
            $show->field('title');
            $show->field('content');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $user = Admin::user();
        return Form::make(new Affiche(), function (Form $form) use ($user) {
            $form->display('id');
            if ($user->is_admin == 1) {
                $form->select('mechanism_id', '所属机构')
                    ->options(Administrator::where('is_admin', -1)
                        ->pluck('name', 'id')->toArray());
            }
            $form->text('title');
            if (Admin::user()->is_admin == -1) {
                $form->hidden('mechanism_id')->default(Admin::user()->id);
            }
            $form->textarea('content')->rows(10);
        
            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
